<?php


namespace App\Repositories;


use App\Models\Shelves as Model;
use App\Traits\CodeTrait;
use App\Traits\Logs;
use Exception;
use LTools\Repositories\RepositoryAbstract;

class Shelves extends RepositoryAbstract
{
    use CodeTrait, Logs;

    /**
     * Shelves constructor.
     * @param Model $model
     * @author luffyzhao@vip.126.com
     */
    public function __construct(Model $model)
    {
        $this->model = $model;
    }

    /**
     * @param array $attributes
     * @param int|null $perPage
     * @param array $columns
     * @param string $pageName
     * @param int|null $page
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     * @author luffyzhao@vip.126.com
     */
    public function paginate(array $attributes, int $perPage = null, array $columns = ['*'], $pageName = 'page', int $page = null)
    {
        return $this->model->with(['tally', 'warehousing', 'product', 'location'])->where(
            $attributes
        )->paginate($perPage, $columns, $pageName, $page);
    }

    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model
     */
    public function edit($id){
        $model = $this->model->with(['product'])->findOrFail($id);
        /** @var Location $location */
        $model->setAttribute('location', app(Location::class)->free($model->getAttribute('attribute')));
        return $model;
    }

    /**
     * @param array $attributes
     * @return bool|\Illuminate\Database\Eloquent\Model
     * @author luffyzhao@vip.126.com
     */
    public function create(array $attributes = [])
    {
        $attributes['code'] = $this->unique(7, 'S' . date('Ymd'));
        $model = parent::create($attributes);

        $this->recordLogs($model, '创建上架单');

        return $model;
    }

    /**
     * @param $id
     * @param array $attributes
     * @return \App\Models\Tally
     * @throws Exception
     * @throws \Throwable
     * @author luffyzhao@vip.126.com
     */
    public function shelves($id, array $attributes = [])
    {
        /** @var \App\Models\Tally $model */
        $model = $this->model->newQuery()->where('id', '=', $id)->lockForUpdate()->first();
        if ($model->getAttribute('status') === 0) {

            try {
                /** @var \App\Models\Location $location */
                $location = \App\Models\Location::where('code', '=', $attributes['code'])
                    ->where('attribute', '=', $model->getAttribute('attribute'))
                    ->firstOrFail();
                // 货架位产品加 1
                $location->increment('count');
            } catch (Exception $exception) {
                throw new Exception('货架属性不正确!');
            }


            $model->setAttribute('location_id', $location->getKey());
            $model->setAttribute('status', 1);
            $model->saveOrFail();

            // 添加产品批次库存
            $data = $model->only(['warehousing_id', 'product_id', 'attribute', 'quantity', 'batch', 'barcode', 'location_id']);
            $data['tally_id'] = $model->getKey();
            $data['customer_id'] = $model->product->getAttribute('customer_id');
            /** @var  BatchInventory $batch */
            $batch = app(BatchInventory::class);
            $batch->create($data);

            // 添加产品库存
            if ($model->getAttribute('attribute') === 0) {
                $model->product->inventory()->increment('usable', $model->getAttribute('quantity'));
            } else if ($model->getAttribute('attribute') === 1) {
                $model->product->inventory()->increment('unusable', $model->getAttribute('quantity'));
            }

            $this->recordLogs($model, '上架单完成');
            return $model;
        }
        throw new Exception('上架单状态不正确不能完成');
    }
}
